package com.imti.jsonparsedemo;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonParseUtil
{

    public static WeatherResponse<WeatherResult<WeatherRealtime>> parseCityWeatherByGson(
        String json)
    {
        WeatherResponse<WeatherResult<WeatherRealtime>> wr = null;

        Gson gson = new Gson();

        Type type = new TypeToken<WeatherResponse<WeatherResult<WeatherRealtime>>>()
        {
        }.getType();
        wr = gson.fromJson(json, type);
        return wr;
    }

    public static WeatherResult parseCityWeather(String json) throws JSONException
    {
        WeatherResult wr = new WeatherResult();

        JSONObject response = new JSONObject(json);

        if (response.has("error_code"))
        {
            int errCode = response.getInt("error_code");

            if (errCode == 0)
            {
                if (response.has("result"))
                {
                    JSONObject result = response.getJSONObject("result");

                    if (result.has("city"))
                    {
                        wr.setCity(result.getString("city"));
                    }

                    if (result.has("realtime"))
                    {
                        JSONObject realtime = result.getJSONObject("realtime");

                        WeatherRealtime weatherRealtime = new WeatherRealtime();

                        if (realtime.has("temperature"))
                        {
                            weatherRealtime.setTemperature(realtime.getString("temperature"));
                        }
                        if (realtime.has("humidity"))
                        {
                            weatherRealtime.setHumidity(realtime.getString("humidity"));
                        }
                        if (realtime.has("info"))
                        {
                            weatherRealtime.setInfo(realtime.getString("info"));
                        }
                        if (realtime.has("direct"))
                        {
                            weatherRealtime.setDirect(realtime.getString("direct"));
                        }
                        if (realtime.has("power"))
                        {
                            weatherRealtime.setPower(realtime.getString("power"));
                        }
                        if (realtime.has("aqi"))
                        {
//                            weatherRealtime.setAqi(realtime.getString("aqi"));
                        }

                        wr.setRealtime(weatherRealtime);
                    }
                }
            }
        }

        return wr;
    }
}
